package com.yrot.common.task;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yrot.admin.dto.GetResultExam;
import com.yrot.admin.dto.RelatedStaffResultExam;
import com.yrot.admin.dto.ResultExam;
import com.yrot.admin.entity.SysResult;
import com.yrot.admin.entity.SysTrain;
import com.yrot.admin.service.ISysResultService;
import com.yrot.admin.service.ISysTrainService;
import com.yrot.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 */
@Slf4j
@Component
public class ScheduledService {
    @Autowired
    ISysTrainService trainService;
    @Autowired
    private ISysResultService resultService;

    @Scheduled(fixedRate = 3600000)
    public R scheduled1() {
        log.info("定时任务：发送考试结果=====>>>>>使用fixedRate{}", System.currentTimeMillis());
        LocalDateTime now =LocalDateTime.now();
        QueryWrapper<SysTrain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_send",0);
        List<SysTrain> sysTrainList = trainService.list(queryWrapper);
        List<SysResult> sysResultList = new ArrayList<>();
        for (SysTrain train:sysTrainList) {
            if(train.getTrainEnd().isBefore(now)){//当前时间大于考试结束时间，发送考试结果
                Integer trainId = train.getTrainId();
                ResultExam resultExam = new ResultExam();
                resultExam.setExamId(trainId);
                QueryWrapper<SysResult> resultQueryWrapper = new QueryWrapper<>();
                resultQueryWrapper.eq("train_id",trainId);
                sysResultList = resultService.list(resultQueryWrapper);
                List<RelatedStaffResultExam> relatedStaffResultExams = new ArrayList<>();
                for(SysResult result: sysResultList){
                    RelatedStaffResultExam relatedStaffResultExam = new RelatedStaffResultExam();
                    relatedStaffResultExam.setRelatedstaffId(result.getRelatedstaffId());
                    if(result.getIsPass()!=null){
                        relatedStaffResultExam.setStatus(result.getIsPass()==0?2:1);
                    }else{
                        relatedStaffResultExam.setStatus(3);
                    }
                    relatedStaffResultExams.add(relatedStaffResultExam);
                }
                if(relatedStaffResultExams.size()>0){
                    resultExam.setRelatedStaffs(relatedStaffResultExams);
                    String jsonString = JSONObject.toJSONString(resultExam);
                    String ans = testPostUrl("http://localhost:8070/RelatedExam/SaveExamResult",jsonString);
                    JSONObject jsonObject = JSONObject.parseObject(ans);
                    System.out.println("statusCode:" + jsonObject.get("statusCode"));
                    System.out.println("statusMsg:" + jsonObject.get("statusMsg"));
                    if("成功".equals(jsonObject.get("statusMsg"))){
                        train.setIsSend(1);
                        trainService.saveOrUpdate(train);
                    }
                }
            }
        }
        return R.ok();
    }
    public String testPostUrl(String url, String jsonString) {
        RestTemplate restTemplate = new RestTemplate();
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<String>(jsonString, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
        String ans = responseEntity.getBody();//{"statusCode": 0,"statusMsg": "成功"}
        System.out.println(ans);
        return ans;
    }
    @Scheduled(fixedRate = 60000)
    public R scheduled2() {
        log.info("定时任务：改变考试状态=====>>>>>使用fixedRate{}", System.currentTimeMillis());
        LocalDateTime now =LocalDateTime.now();
        QueryWrapper<SysTrain> queryWrapper = new QueryWrapper<>();
        List<SysTrain> sysTrainList = trainService.list(queryWrapper);
        for (SysTrain train:sysTrainList) {
            if(train.getTrainStatus()!=2){
                if(train.getTrainStart().isBefore(now) && train.getTrainEnd().isAfter(now)){//当前时间大于考试开始时间，改变考试状态
                    train.setTrainStatus(1);
                    trainService.saveOrUpdate(train);
                }else if(train.getTrainEnd().isBefore(now)){
                    train.setTrainStatus(2);
                    trainService.saveOrUpdate(train);
                }
            }
        }
        return R.ok();
    }
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        return scheduler;
    }
}